package com.hubu.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hubu.mapper.CommodityMapper;
import com.hubu.pojo.Commodity;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.List;

@Service
public class CommodityService {
    @Resource
    private CommodityMapper commodityMapper;

    /**
     * 添加一个商品
     * @param commodity
     */
    public int addCommodity(Commodity commodity) {
        return commodityMapper.insert(commodity);
    }

    /**
     * 获取所有的商品列表, 返回分页
     *
     * @param name
     * @param pageNum
     * @return
     */
    public PageInfo<Commodity> getCommodities(String name, int pageNum) {
        PageHelper.startPage(pageNum, 5);

        // 1. 首先根据条件查询(没有被删除的)，注意分页逻辑必须先写，因为最后会给到sql语句
        Example example = new Example(Commodity.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("isDeleted", 0);
        criteria.andLike("name", '%' + name + '%');
        List<Commodity> commodities = commodityMapper.selectByExample(example);

        // 2. 然后进行分页
        PageInfo<Commodity> pageInfo = new PageInfo<Commodity>(commodities);
        return pageInfo;
    }

    /**
     * 根据id删除商品，逻辑删除
     * @param id
     */
    public void deleteComById(Long id) {
        Example example = new Example(Commodity.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("id", id);

        // 找到商品并将isDeleted设置为1，表示删除
        Commodity commodity = new Commodity();
        commodity.setIsDeleted(1);
        commodityMapper.updateByExampleSelective(commodity, example);
    }

    /**
     * 根据id更新商品信息
     * @param commodity
     */
    public void editComById(Commodity commodity) {
        Example example = new Example(Commodity.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("id", commodity.getId());
        System.out.println("================");
        System.out.println(commodity);
        System.out.println("===================");
        // 进行更新
        commodityMapper.updateByExampleSelective(commodity, example);
    }

    /**
     * 通过id获取一个商品信息
     * @param id
     */
    public Commodity getCommodityById(Long id) {
        Example example = new Example(Commodity.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("id", id);
        return commodityMapper.selectOneByExample(example);
    }
}
